package jp.dip.ysato.excitewidget;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class LoginActivity extends Activity {
	
	private Button okbutton;
	private Button cancelbutton;
	private EditText user;
	private EditText pass;
	class LoginTest extends AsyncTask<String, Void, Boolean> {
		private final String LOGIN="http://www.excite.co.jp/?pname=xmy&brand=xcit&targeturl=http%3A%2F%2Fwww.excite.co.jp%2F&lin=1";
		@Override
		protected Boolean doInBackground(String... arg0) {
			// TODO Auto-generated method stub
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				HttpPost post = new HttpPost(LOGIN);
				List<NameValuePair> param = new ArrayList<NameValuePair>();
				param.add(new BasicNameValuePair("acctname", arg0[0]));
				param.add(new BasicNameValuePair("passwd", arg0[1]));
				post.setEntity(new UrlEncodedFormEntity(param, HTTP.UTF_8));
				HttpResponse res = httpClient.execute(post);
				ByteArrayInputStream in = new ByteArrayInputStream(EntityUtils.toByteArray(res.getEntity()));
				httpClient.getConnectionManager().shutdown();
				BufferedReader br = new BufferedReader(new InputStreamReader(in));
				String line;
				while((line = br.readLine()) != null) {
					if (line.indexOf("error_msg") > 0)
						return false;
				}
				DBHelper dbhelper = new DBHelper(LoginActivity.this);
				SQLiteDatabase db = dbhelper.getWritableDatabase();
				db.execSQL("DELETE FROM account");
				ContentValues cv = new ContentValues();
				cv.put("user", arg0[0]);
				cv.put("password", arg0[1]);
				db.insert("account", null, cv);
				db.close();
				Intent service = new Intent(LoginActivity.this, ExciteService.class);
				startService(service);
				return true;
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return false;
		}
		@Override
		protected void onPostExecute(Boolean success) {
			if (!success) {
				AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
				builder.setTitle(R.string.LoginFailed);
				builder.setPositiveButton(android.R.string.ok, null);
				AlertDialog dialog = builder.create();
				dialog.show();
			} else 
				finish();
		}
	}
	private final OnClickListener onclick = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			if (okbutton.equals(arg0)) {
				String u = user.getText().toString();
				String p = pass.getText().toString();
				new LoginTest().execute(new String[] {u, p});
			} else if (cancelbutton.equals(arg0)) {
				finish();
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		okbutton = (Button) findViewById(R.id.ok_button);
		cancelbutton = (Button) findViewById(R.id.cancel_button);
		user = (EditText) findViewById(R.id.editText1);
		pass = (EditText) findViewById(R.id.editText2);
		okbutton.setOnClickListener(onclick);
		cancelbutton.setOnClickListener(onclick);
	}
}
